'use client'

import { useState, useEffect } from 'react'
import { motion } from 'framer-motion'
import { Play, Settings, BookOpen, Target, Clock, Trophy, ArrowLeft } from 'lucide-react'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { ALL_TOPICS } from '@/data/topics-index'
import { QUESTION_BANK, TOPIC_ID_TO_NAME } from '@questions'
import { useRouter } from 'next/navigation'

interface Topic {
  id: string
  name: string
  category: string
  difficulty: number
  gradeLevel: number[]
}

interface PracticeSettings {
  selectedTopics: string[]
  difficulty: number[]
  questionCount: number
  timeLimit: number | null
}

export default function FreePracticePage() {
  const [topics, setTopics] = useState<Topic[]>([])
  const [settings, setSettings] = useState<PracticeSettings>({
    selectedTopics: [],
    difficulty: [1, 2, 3, 4, 5],
    questionCount: 10,
    timeLimit: null
  })
  const [isLoading, setIsLoading] = useState(true)
  const [error, setError] = useState('')
  const [showSettings, setShowSettings] = useState(false)
  const router = useRouter()

  useEffect(() => {
    loadTopics()
  }, [])

  const loadTopics = async () => {
    try {
      setIsLoading(true)

      // 使用本地题库数据
      const formattedTopics = ALL_TOPICS.map(topic => ({
        id: topic.id,
        name: topic.name,
        category: topic.category,
        difficulty: topic.difficulty,
        gradeLevel: topic.gradeLevel
      }))
      setTopics(formattedTopics)
    } catch (err) {
      console.error('加载知识点错误:', err)
      setError('加载知识点时发生错误')
    } finally {
      setIsLoading(false)
    }
  }

  const handleTopicToggle = (topicId: string) => {
    setSettings(prev => ({
      ...prev,
      selectedTopics: prev.selectedTopics.includes(topicId)
        ? prev.selectedTopics.filter(id => id !== topicId)
        : [...prev.selectedTopics, topicId]
    }))
  }

  const handleDifficultyToggle = (difficulty: number) => {
    setSettings(prev => ({
      ...prev,
      difficulty: prev.difficulty.includes(difficulty)
        ? prev.difficulty.filter(d => d !== difficulty)
        : [...prev.difficulty, difficulty].sort()
    }))
  }

  const startPractice = () => {
    if (settings.selectedTopics.length === 0) {
      alert('请至少选择一个知识点')
      return
    }

    if (settings.difficulty.length === 0) {
      alert('请至少选择一个难度等级')
      return
    }

    // 检查是否有可用题目
    const availableCount = getAvailableQuestionCount();
    if (availableCount === 0) {
      alert('所选知识点和难度没有可用题目，请调整选择')
      return
    }

    // 如果只选择了一个知识点，直接跳转到该知识点的练习
    if (settings.selectedTopics.length === 1) {
      const topicId = settings.selectedTopics[0];
      const topic = topics.find(t => t.id === topicId);
      if (topic) {
        const params = new URLSearchParams({
          topicId: topic.id,
          topicName: topic.name,
          difficulty: settings.difficulty.join(','),
          count: Math.min(settings.questionCount, availableCount).toString(),
          timeLimit: settings.timeLimit?.toString() || ''
        })
        router.push(`/practice/session?${params.toString()}`)
      }
    } else {
      // 多个知识点的练习（需要session页面支持）
      const params = new URLSearchParams({
        topics: settings.selectedTopics.join(','),
        difficulty: settings.difficulty.join(','),
        count: Math.min(settings.questionCount, availableCount).toString(),
        timeLimit: settings.timeLimit?.toString() || ''
      })
      router.push(`/practice/session?${params.toString()}`)
    }
  }

  const getDifficultyLabel = (difficulty: number) => {
    const labels = { 1: '入门', 2: '基础', 3: '进阶', 4: '高级', 5: '竞赛' }
    return labels[difficulty as keyof typeof labels] || '未知'
  }

  const getDifficultyDescription = (difficulty: number) => {
    const descriptions = {
      1: '适合1-3年级，基础概念',
      2: '适合3-4年级，基础应用',
      3: '适合4-6年级，综合运用',
      4: '适合已学方程，进阶解题',
      5: '适合竞赛冲刺，难度较高'
    }
    return descriptions[difficulty as keyof typeof descriptions] || ''
  }

  const getDifficultyColor = (difficulty: number) => {
    const colors = {
      1: 'bg-green-100 text-green-800 border-green-300',
      2: 'bg-blue-100 text-blue-800 border-blue-300',
      3: 'bg-yellow-100 text-yellow-800 border-yellow-300',
      4: 'bg-orange-100 text-orange-800 border-orange-300',
      5: 'bg-red-100 text-red-800 border-red-300'
    }
    return colors[difficulty as keyof typeof colors] || 'bg-gray-100 text-gray-800 border-gray-300'
  }

  const getAvailableQuestionCount = () => {
    let totalQuestions = 0;

    if (settings.selectedTopics.length === 0) {
      // 如果没有选择知识点，计算所有知识点的题目数量
      Object.values(QUESTION_BANK).forEach(topicQuestions => {
        const filteredQuestions = topicQuestions.filter(q => settings.difficulty.includes(q.difficulty));
        totalQuestions += filteredQuestions.length;
      });
    } else {
      // 计算选中知识点的题目数量
      settings.selectedTopics.forEach(topicId => {
        // 使用 TOPIC_ID_TO_NAME 映射获取题库键名
        const questionBankKey = TOPIC_ID_TO_NAME[topicId];
        if (questionBankKey) {
          const topicQuestions = QUESTION_BANK[questionBankKey] || [];
          const filteredQuestions = topicQuestions.filter(q => settings.difficulty.includes(q.difficulty));
          totalQuestions += filteredQuestions.length;
        }
      });
    }

    return totalQuestions;
  }

  const groupedTopics = topics.reduce((acc, topic) => {
    if (!acc[topic.category]) {
      acc[topic.category] = []
    }
    acc[topic.category].push(topic)
    return acc
  }, {} as Record<string, Topic[]>)

  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="text-center">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600 mx-auto mb-4"></div>
          <p className="text-gray-600">加载练习设置中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gradient-to-br from-blue-50 via-indigo-50 to-purple-50 dark:from-gray-900 dark:via-blue-900 dark:to-purple-900 p-6">
      <div className="max-w-6xl mx-auto">
        {/* 返回按钮 */}
        <motion.div
          initial={{ opacity: 0, x: -20 }}
          animate={{ opacity: 1, x: 0 }}
          className="mb-4"
        >
          <Button
            variant="outline"
            onClick={() => router.push('/dashboard')}
            className="flex items-center gap-2"
          >
            <ArrowLeft className="w-4 h-4" />
            返回学习仪表盘
          </Button>
        </motion.div>

        {/* 页面标题 */}
        <motion.div
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          className="mb-8 text-center"
        >
          <h1 className="text-3xl font-bold text-gray-800 dark:text-gray-200 mb-2">
            自由练习
          </h1>
          <p className="text-gray-600 dark:text-gray-300">
            自主选择知识点和难度，定制您的专属练习
          </p>
        </motion.div>

        {/* 错误提示 */}
        {error && (
          <motion.div
            initial={{ opacity: 0, y: -10 }}
            animate={{ opacity: 1, y: 0 }}
            className="mb-6 p-4 rounded-lg bg-red-100 border border-red-300 text-red-700"
          >
            {error}
          </motion.div>
        )}

        <div className="grid lg:grid-cols-3 gap-6">
          {/* 练习设置 */}
          <div className="lg:col-span-2 space-y-6">
            {/* 知识点选择 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.1 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <BookOpen className="w-5 h-5" />
                    选择知识点
                  </CardTitle>
                  <CardDescription>
                    选择您想要练习的知识点（已选择 {settings.selectedTopics.length} 个）
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    {Object.entries(groupedTopics).map(([category, categoryTopics]) => (
                      <div key={category}>
                        <h4 className="font-medium text-gray-700 dark:text-gray-300 mb-2">
                          {category}
                        </h4>
                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-2">
                          {categoryTopics.map(topic => (
                            <div
                              key={topic.id}
                              onClick={() => handleTopicToggle(topic.id)}
                              className={`p-3 rounded-lg border cursor-pointer transition-all duration-200 ${
                                settings.selectedTopics.includes(topic.id)
                                  ? 'bg-blue-100 border-blue-300 text-blue-800'
                                  : 'bg-white/50 border-gray-200 hover:bg-white/70'
                              }`}
                            >
                              <div className="flex items-center justify-between">
                                <span className="text-sm font-medium">{topic.name}</span>
                                <span className={`px-2 py-1 rounded-full text-xs ${getDifficultyColor(topic.difficulty)}`}>
                                  {getDifficultyLabel(topic.difficulty)}
                                </span>
                              </div>
                            </div>
                          ))}
                        </div>
                      </div>
                    ))}
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 难度选择 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.2 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Target className="w-5 h-5" />
                    选择难度
                  </CardTitle>
                  <CardDescription>
                    选择题目难度等级（已选择 {settings.difficulty.length} 个等级）
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="space-y-4">
                    <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-5 gap-3">
                      {[1, 2, 3, 4, 5].map(difficulty => (
                        <div
                          key={difficulty}
                          onClick={() => handleDifficultyToggle(difficulty)}
                          className={`p-4 rounded-lg border cursor-pointer transition-all duration-200 text-center ${
                            settings.difficulty.includes(difficulty)
                              ? getDifficultyColor(difficulty) + ' border-2'
                              : 'bg-white/50 border-gray-200 hover:bg-white/70'
                          }`}
                        >
                          <div className="text-2xl font-bold mb-1">⭐{'⭐'.repeat(difficulty - 1)}</div>
                          <div className="text-sm font-semibold mb-1">{getDifficultyLabel(difficulty)}</div>
                          <div className="text-xs text-gray-600 dark:text-gray-400">{getDifficultyDescription(difficulty)}</div>
                        </div>
                      ))}
                    </div>
                    <div className="p-3 bg-blue-50 dark:bg-blue-900/20 rounded-lg border border-blue-200 dark:border-blue-800">
                      <p className="text-sm text-blue-800 dark:text-blue-300">
                        💡 <strong>提示：</strong>4-5星难度的题目需要用方程求解，建议已学过一元一次方程的学生选择。1-3星难度适合使用算术方法解题。
                      </p>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 练习参数 */}
            <motion.div
              initial={{ opacity: 0, y: 20 }}
              animate={{ opacity: 1, y: 0 }}
              transition={{ delay: 0.3 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Settings className="w-5 h-5" />
                    练习参数
                  </CardTitle>
                  <CardDescription>
                    设置题目数量和时间限制
                  </CardDescription>
                </CardHeader>
                <CardContent>
                  <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        题目数量
                      </label>
                      <select
                        value={settings.questionCount}
                        onChange={(e) => setSettings(prev => ({ ...prev, questionCount: Number(e.target.value) }))}
                        className="w-full px-3 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value={5}>5道题</option>
                        <option value={10}>10道题</option>
                        <option value={15}>15道题</option>
                        <option value={20}>20道题</option>
                        <option value={30}>30道题</option>
                      </select>
                    </div>
                    <div>
                      <label className="block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">
                        时间限制
                      </label>
                      <select
                        value={settings.timeLimit || ''}
                        onChange={(e) => setSettings(prev => ({
                          ...prev,
                          timeLimit: e.target.value ? Number(e.target.value) : null
                        }))}
                        className="w-full px-3 py-2 rounded-lg bg-white/20 backdrop-blur-sm border border-white/30 text-gray-700 focus:outline-none focus:ring-2 focus:ring-blue-500"
                      >
                        <option value="">无限制</option>
                        <option value={300}>5分钟</option>
                        <option value={600}>10分钟</option>
                        <option value={900}>15分钟</option>
                        <option value={1200}>20分钟</option>
                        <option value={1800}>30分钟</option>
                      </select>
                    </div>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          </div>

          {/* 练习摘要和开始按钮 */}
          <div className="space-y-6">
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.4 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="flex items-center gap-2">
                    <Trophy className="w-5 h-5" />
                    练习摘要
                  </CardTitle>
                </CardHeader>
                <CardContent className="space-y-4">
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">知识点</span>
                    <span className="font-medium">{settings.selectedTopics.length} 个</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">难度等级</span>
                    <span className="font-medium">{settings.difficulty.length} 个</span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">题目数量</span>
                    <span className="font-medium">
                      {settings.questionCount} 道
                      <span className="text-sm text-gray-500 ml-1">
                        (可用: {getAvailableQuestionCount()} 道)
                      </span>
                    </span>
                  </div>
                  <div className="flex items-center justify-between">
                    <span className="text-gray-600">时间限制</span>
                    <span className="font-medium">
                      {settings.timeLimit ? `${Math.floor(settings.timeLimit / 60)} 分钟` : '无限制'}
                    </span>
                  </div>

                  <div className="pt-4 border-t border-gray-200">
                    <Button
                      onClick={startPractice}
                      className="w-full bg-gradient-to-r from-blue-500 to-purple-600 hover:from-blue-600 hover:to-purple-700 text-white"
                      disabled={settings.selectedTopics.length === 0 || settings.difficulty.length === 0}
                    >
                      <Play className="w-4 h-4 mr-2" />
                      开始练习
                    </Button>
                  </div>
                </CardContent>
              </Card>
            </motion.div>

            {/* 快速设置 */}
            <motion.div
              initial={{ opacity: 0, x: 20 }}
              animate={{ opacity: 1, x: 0 }}
              transition={{ delay: 0.5 }}
            >
              <Card glassmorphism className="backdrop-blur-xl">
                <CardHeader>
                  <CardTitle className="text-lg">快速设置</CardTitle>
                </CardHeader>
                <CardContent className="space-y-3">
                  <Button
                    variant="outline"
                    className="w-full justify-start"
                    onClick={() => {
                      setSettings(prev => ({
                        ...prev,
                        selectedTopics: topics.filter(t => t.difficulty <= 2).map(t => t.id),
                        difficulty: [1, 2],
                        questionCount: 10,
                        timeLimit: null
                      }))
                    }}
                  >
                    基础练习
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start"
                    onClick={() => {
                      setSettings(prev => ({
                        ...prev,
                        selectedTopics: topics.filter(t => t.difficulty >= 3 && t.difficulty <= 4).map(t => t.id),
                        difficulty: [3, 4],
                        questionCount: 15,
                        timeLimit: 900
                      }))
                    }}
                  >
                    进阶挑战
                  </Button>
                  <Button
                    variant="outline"
                    className="w-full justify-start"
                    onClick={() => {
                      setSettings(prev => ({
                        ...prev,
                        selectedTopics: topics.filter(t => t.difficulty === 5).map(t => t.id),
                        difficulty: [5],
                        questionCount: 20,
                        timeLimit: 1200
                      }))
                    }}
                  >
                    竞赛模式
                  </Button>
                </CardContent>
              </Card>
            </motion.div>
          </div>
        </div>
      </div>
    </div>
  )
}
